package com.dzjcloud.dzj.gateway.config;



import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dzjcloud.dzj.gateway.dto.Gateway;
import com.dzjcloud.dzj.gateway.service.impl.DynamicRouteServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: 董泽建
 * @create: 2024-01-17 10:58
 * @Description:
 */
@Slf4j
@Component
public class RedisMessageListener implements MessageListener {

    @Resource
    private StringRedisSerializer stringRedisSerializer;

    @Autowired
    private DynamicRouteServiceImpl dynamicRouteService;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //频道名称
        String channel = stringRedisSerializer.deserialize(message.getChannel());
        //消息内容
        String body = stringRedisSerializer.deserialize(message.getBody());
        log.info("监听到路由信息:{}", body);

        List<Gateway> gateways = JSONArray.parseArray(body, Gateway.class);
        dynamicRouteService.refresh(gateways);
    }
}
